﻿using Newtonsoft.Json;
using System.Net.Http.Headers;

namespace Luka;

/// <summary>
/// Http请求操作类
/// </summary>
public sealed class HttpExtensions
{
    /// <summary>
    /// get请求
    /// </summary>
    /// <param name="url">请求路径</param>
    /// <returns></returns>
    public static string GetResponse(string url)
    {
        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = httpClient.GetAsync(url).Result;
        string result = string.Empty;
        if (response.IsSuccessStatusCode)
        {
            result = response.Content.ReadAsStringAsync().Result;
        }
        return result;
    }

    /// <summary>
    /// get请求
    /// </summary>
    /// <param name="url">请求路径</param>
    /// <returns></returns>
    public static T? GetResponse<T>(string url)
        where T : class, new()
    {
        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = httpClient.GetAsync(url).Result;
        string result = string.Empty;
        if (response.IsSuccessStatusCode)
        {
            result = response.Content.ReadAsStringAsync().Result;
        }
        return JsonConvert.DeserializeObject<T>(result);
    }

    /// <summary>
    /// post请求
    /// </summary>
    /// <param name="url">请求路径</param>
    /// <param name="postData">post数据</param>
    /// <returns></returns>
    public static string PostResponse(string url, string postData)
    {
        HttpContent httpContent = new StringContent(postData);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
        string result = string.Empty;
        if (response.IsSuccessStatusCode)
        {
            result = response.Content.ReadAsStringAsync().Result;
        }
        return result;
    }

    /// <summary>
    /// 发起post请求
    /// </summary>
    /// <param name="url">url</param>
    /// <param name="postData">post数据</param>
    /// <returns></returns>
    public static T? PostResponse<T>(string url, string postData) where T : class, new()
    {
        HttpContent httpContent = new StringContent(postData);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
        string result = string.Empty;
        if (response.IsSuccessStatusCode)
        {
            result = response.Content.ReadAsStringAsync().Result;
        }
        return JsonConvert.DeserializeObject<T>(result);
    }
}